let baseUrl = "https://hc.hckj88.net"

// 将对象转换为查询字符串
const objectToQueryString = (obj) => {
	if (!obj || typeof obj !== "object") return ""

	const params = []
	for (const key in obj) {
		if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
			params.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
		}
	}
	return params.join("&")
}

// 构建完整的URL（处理GET请求参数）
const buildUrl = (baseUrl, path, method, data) => {
	console.log(baseUrl, path, method, data, 'buildUrl');

	let fullUrl = baseUrl + path
	if (method === "get") {
		const queryString = objectToQueryString(data)
		console.log(queryString, 'queryString');

		if (queryString) {
			// 检查URL是否已经包含查询参数
			const separator = fullUrl.includes("?") ? "&" : "?"
			fullUrl += separator + queryString
		}
	}

	return fullUrl
}

// 不带token请求
const httpRequest = (opts, data) => {
	const fullUrl = buildUrl(baseUrl, opts.url, opts.method, opts.data)
	console.log(fullUrl, 'fullUrl');

	const httpDefaultOpts = {
		url: fullUrl,
		// GET请求不需要在body中传递data，已经拼接到URL中了
		data: opts.method.toLowerCase() === "get" ? {} : opts.data,
		method: opts.method,
		header: opts.method == "get" ? {
			"X-Requested-With": "XMLHttpRequest",
			Accept: "application/json",
			"Content-Type": "application/json; charset=UTF-8",
		} : {
			"X-Requested-With": "XMLHttpRequest",
			"Content-Type": "application/json; charset=UTF-8",
		},
		dataType: "json",
	}

	const promise = new Promise((resolve, reject) => {
		uni
			.request(httpDefaultOpts)
			.then((res) => {
				resolve(res[1])
			})
			.catch((response) => {
				reject(response)
			})
	})
	return promise
}

//带Token请求
const httpTokenRequest = (opts, data) => {
	const token = uni.getStorageSync("token")

	if (token == "" || token == undefined || token == null) {
		uni.showToast({
			title: "账号已过期，请重新登录",
			icon: "none",
			complete: () => {
				uni.reLaunch({
					url: "/pages/user/index",
				})
			},
		})
		return Promise.reject(new Error("Token不存在"))
	} else {
		// 构建完整URL
		const fullUrl = buildUrl(baseUrl, opts.url, opts.method, opts.data)

		const httpDefaultOpts = {
			url: fullUrl,
			// GET请求不需要在body中传递data，已经拼接到URL中了
			data: opts.method.toLowerCase() === "get" ? {} : opts.data,
			method: opts.method,
			header: opts.method == "get" ? {
				token: token,
				"X-Requested-With": "XMLHttpRequest",
				Accept: "application/json",
				"Content-Type": "application/json; charset=UTF-8",
			} : {
				token: token,
				"X-Requested-With": "XMLHttpRequest",
				"Content-Type": "application/json; charset=UTF-8",
			},
			dataType: opts.dataType || "json",
		}

		const promise = new Promise((resolve, reject) => {
			uni
				.request(httpDefaultOpts)
				.then((res) => {
					if (res[1].data.code == 200) {
						resolve(res[1])
					} else {
						if (res[1].data.code == 5000) {
							uni.reLaunch({
								url: "/pages/user/index",
							})
							uni.clearStorageSync()
						} else {
							resolve(res[1])
						}
					}
				})
				.catch((response) => {
					reject(response)
				})
		})
		return promise
	}
}

// 拦截器
const hadToken = () => {
	const token = uni.getStorageSync("token")

	if (token == "" || token == undefined || token == null) {
		uni.showToast({
			title: "账号已过期，请重新登录",
			icon: "none",
			complete: () => {
				uni.reLaunch({
					url: "/pages/user/index",
				})
			},
		})
		return false
	}
	return true
}

export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	hadToken,
}